package 笔试2.微软.one;

import org.junit.Test;

//字符串编码
public class Main {

    @Test
    public void test() {
//        System.out.println(solution("ABCDDDEFG",2));
        System.out.println(solution("ABBBCCDDCCC",3));
    }

    public int solution(String s, int k) {
        int minLen = 99999;
        for (int i = 0; i < s.length()-1; i++) {
            if(i+k>=s.length())break;
            String mergestr = mergestr(s, i, i + k-1);
//            System.out.println(mergestr);
            mergestr = bianma(mergestr);
//            System.out.println(mergestr);
//            System.out.println();
            if(mergestr.length()<minLen){
                minLen=mergestr.length();
            }
        }
        return minLen;
    }
    private String mergestr(String s,int l, int r) {
        String lf = s.substring(0,l);
        String rt="";
        if(r+1<s.length()) {
            rt = s.substring(r + 1, s.length());
        }
        return lf+rt;
    }
    private String bianma(String s) {
        char[] c = s.toCharArray();
        char old = '#';
        String res = "";
        int i=0;
        while (i<s.length()){
            char cur = c[i];
            if(cur!=old){
                int gs=1;
                i++;
                while(i-1>=0 && i<s.length() && c[i-1]==c[i]){
                    gs++;
                    i++;
                }
                //
                if(gs==1){
                    res = cur+res;
                }
                else if(gs>1){
                    res = cur+""+gs+res;
                }
                old=cur;
            }
        }
        return new StringBuilder(res).reverse().toString();
    }
}
